package com.mingtu.jgspatrol.activity;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.FireTypeBean;
import com.mingtu.jgspatrol.databinding.ActivityFireTaskSureBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class FireTaskSureActivity extends MyBaseActivity<ActivityFireTaskSureBinding> {
    private ArrayList<String> fireStationList = new ArrayList<>();
    private ArrayList<String> fireLevelList = new ArrayList<>();
    private ArrayList<String> fireTypeList = new ArrayList<>();
    private ArrayList<String> fireStatusList = new ArrayList<>();
    private ArrayList<String> resourceTypeList = new ArrayList<>();

    private String[] fireStationArray = {"有火情", "非火情", "重复预警", "误报"};
    private String[] typeArray = {"GRADE_TYPE", "FIRE_TYPE", "FIRE_STATUS", "RESOURCE_TYPE"};
    private int[] positionArray = {0, 0, 0, 0, 0};

    private String[] choseArray = {"请选择等级", "请选择类型", "请选择状态"};
    private int textNum = 0;
    private int confirmType = 5;
    private String taskId;
    private List<String> mylist = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fire_task_sure;
    }

    @Override
    protected void initView() {
        setModuleTitle("火情确认");

        binding.editDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textNum -= count;
                binding.tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textNum += count;
                binding.tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
                MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                String str = MyUtills.getEditText(binding.editDescribe);
                binding.editDescribe.setSelection(str.length());
            }
        });

        int screenWidth = ScreenUtils.getScreenWidth();
        int itemWidth = (screenWidth - SizeUtils.dp2px(5) * 2 - SizeUtils.dp2px(15) * 4) / 3;
        binding.reportPictureVideo.setItemWidth(itemWidth);
    }

    @Override
    protected void initData() {
        for (String s : fireStationArray) {
            fireStationList.add(s);
        }

        for (String s : typeArray) {
            getFireType(s);
        }
        addClickListener(this,binding.layoutFireStation, binding.layoutFireLevel, binding.layoutFireType, binding.layoutFireStatus, binding.layoutResourceType,binding.submit);
    }

    @Override
    protected void getData() {
        taskId = getIntent().getStringExtra("taskId");
        if (StringUtils.isEmpty(taskId)) {
            ToastUtils.showLong(getResources().getString(R.string.data_error));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_fire_station:
                initOptionPicker(0);
                break;
            case R.id.layout_fire_level:
                if (fireLevelList.size() > 0) {
                    initOptionPicker(1);
                } else {
                    ToastUtils.showLong("抱歉，未获取到火情等级数据！");
                }
                break;
            case R.id.layout_fire_type:
                if (fireTypeList.size() > 0) {
                    initOptionPicker(2);
                } else {
                    ToastUtils.showLong("抱歉，未获取到火情类型数据！");
                }
                break;
            case R.id.layout_fire_status:
                if (fireStatusList.size() > 0) {
                    initOptionPicker(3);
                } else {
                    ToastUtils.showLong("抱歉，未获取到火情状态数据！");
                }
                break;
            case R.id.layout_resource_type:
                if (resourceTypeList.size() > 0) {
                    initOptionPicker(4);
                } else {
                    ToastUtils.showLong("抱歉，未获取到所属地资源类型数据！");
                }
                break;
            case R.id.submit:
                if (confirmType == 5) {
                    ToastUtils.showLong("请确认是否有火情");
                    return;
                }
                if (confirmType == 1) {
                    String fireLevel = UIUtils.getTextView(binding.tvFireLevel);
                    String fireType = UIUtils.getTextView(binding.tvFireType);
                    String fireStatus = UIUtils.getTextView(binding.tvFireStatus);
                    String resourceType = UIUtils.getTextView(binding.tvResourceType);

                    if (fireLevel.equals(choseArray[0])) {
                        ToastUtils.showLong("请选择火情等级！");
                        return;
                    }

                    if (fireType.equals(choseArray[1])) {
                        ToastUtils.showLong("请选择火情类型！");
                        return;
                    }

                    if (fireStatus.equals(choseArray[2])) {
                        ToastUtils.showLong("请选择火情状态！");
                        return;
                    }
                    if (resourceType.equals(choseArray[1])) {
                        ToastUtils.showLong("请选择所属地资源类型！");
                        return;
                    }
                }

                List<LinkedHashMap<String, Object>> picVideoUrl = binding.reportPictureVideo.getPicVideoUrl();
                if (picVideoUrl.size() == 0) {
                    ToastUtils.showLong("请上传图片或者视频！");
                    return;
                }
                //每次请求的时候需要重新获取url
                mylist = new ArrayList<>();
                for (int i = 0; i < picVideoUrl.size(); i++) {
                    LinkedHashMap<String, Object> hashMap = picVideoUrl.get(i);
                    String url = (String) hashMap.get("url");
                    mylist.add(url);
                }
                sureFire();
                break;
        }
    }

    /**
     * 条件选择器
     */

    private void initOptionPicker(int type) {//条件选择器初始化
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String typeText = "";
                TextView view = null;
                if (type == 0) {
                    typeText = fireStationList.get(options1);
                    view = binding.tvFireStation;
                    confirmType = options1 + 1;
                    if (options1 == 0) {
                        binding.layoutHaveFire.setVisibility(View.VISIBLE);
                    } else {
                        binding.layoutHaveFire.setVisibility(View.GONE);
                    }

                } else if (type == 1) {
                    typeText = fireLevelList.get(options1);
                    view = binding.tvFireLevel;
                } else if (type == 2) {
                    typeText = fireTypeList.get(options1);
                    view = binding.tvFireType;
                } else if (type == 3) {
                    typeText = fireStatusList.get(options1);
                    view = binding.tvFireStatus;
                } else if (type == 4) {
                    typeText = resourceTypeList.get(options1);
                    view = binding.tvResourceType;
                }
                setText(view, typeText);
                positionArray[type] = options1;

            }
        })

                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setOutSideColor(getResources().getColor(R.color.translucence)) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {

                    }
                })
                .build();

        pvOptions.setSelectOptions(positionArray[type]);
        if (type == 0) {
            pvOptions.setPicker(fireStationList);
        } else if (type == 1) {
            pvOptions.setPicker(fireLevelList);
        } else if (type == 2) {
            pvOptions.setPicker(fireTypeList);
        } else if (type == 3) {
            pvOptions.setPicker(fireStatusList);
        } else if (type == 4) {
            pvOptions.setPicker(resourceTypeList);
        }
        pvOptions.show();

    }

    private void setText(TextView textView, String s) {
        try {
            textView.setText(s + "");
            textView.setTextColor(getResources().getColor(R.color.text_color333));
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认火情
     */
    private void sureFire() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("confirmType", confirmType + "");
        hashMap.put("fireStatus", UIUtils.getTextView(binding.tvFireStatus));
        hashMap.put("fireType", UIUtils.getTextView(binding.tvFireType));
        hashMap.put("gradeType", UIUtils.getTextView(binding.tvFireLevel));
        hashMap.put("memo", UIUtils.getEditText(binding.editDescribe));
        hashMap.put("resourceType", UIUtils.getTextView(binding.tvResourceType));
        hashMap.put("taskId", taskId);
        hashMap.put("urlList", mylist);
        String str = GsonUtils.toJson(hashMap);

        OkGo.<String>post(MyConstant.POST_CONFIRM_FIRE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String success = jsonObject.getString("msg");
                            if (success.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("提交成功！");

                                //实例化Timer类 ,守护线程，不在后台一直运行
                                Timer timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        ActivityUtil.removeActivity(FireTaskSureActivity.this);
                                        List<Activity> activities = ActivityUtil.getActivityList();
                                        for (Activity activity : activities) {
                                            String name = activity.getClass().getName();
                                            if (name.equals(AppUtils.getAppPackageName() + ".activity.FireTaskActivity")) {
                                                ActivityUtil.removeActivity(activity);
                                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_RECEIVE_TASK));
                                            }
                                        }

                                    }
                                }, Constant.TIMER_TIME);

                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 获取各个选项的数据类型
     *
     * @param type
     */
    private void getFireType(String type) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", type);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FIRE_DICT + "/" + type)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                FireTypeBean fireTypeBean = new FireTypeBean();
                                fireTypeBean = gson.fromJson(result, FireTypeBean.class);

                                List<FireTypeBean.TagsBean> tagsBeans = fireTypeBean.getTags();

                                if (tagsBeans != null) {
                                    if (tagsBeans.size() > 0) {
                                        for (FireTypeBean.TagsBean tagsBean : tagsBeans) {
                                            String value = tagsBean.getValue();
                                            if (type.equals(typeArray[0])) {
                                                fireLevelList.add(value);
                                            } else if (type.equals(typeArray[1])) {
                                                fireTypeList.add(value);
                                            } else if (type.equals(typeArray[2])) {
                                                fireStatusList.add(value);
                                            } else if (type.equals(typeArray[3])) {
                                                resourceTypeList.add(value);
                                            }
                                        }
                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


}